package com.oa.ylms.apps.dao.organization.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.ylms.apps.constants.IDEDStates;
import com.oa.ylms.apps.dao.organization.ISectionInfoDao;
import com.oa.ylms.apps.entity.organization.SectionInfoValue;

public class SectionInfoDaoImpl extends HibernateDaoSupport implements
		ISectionInfoDao {
	List<SectionInfoValue> list;

	@Override
	public int addSectionInfo(SectionInfoValue sectionInfo) throws Exception {
		if(sectionInfo != null){
			this.getHibernateTemplate().save(sectionInfo);
			return sectionInfo.getSectionId();
		}
		return 0;
		
	}

	@Override
	public boolean editSectionInfo(SectionInfoValue sectionInfo)
			throws Exception {
		if(sectionInfo != null){
			try{
			this.getHibernateTemplate().update(sectionInfo);
			}catch(Exception e){
				return false;
			}
		}
		return true;
	}

	@Override
	public SectionInfoValue queryBySectionId(SectionInfoValue sectionInfo)
			throws Exception {
		if(sectionInfo != null){
			return (SectionInfoValue) this.getHibernateTemplate().get(SectionInfoValue.class, sectionInfo.getSectionId());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SectionInfoValue> querySectionInfo(final SectionInfoValue sectionInfo)
			throws Exception {
		String hqlStr = "FROM SectionInfoValue siv WHERE 1=1";
		if(sectionInfo.getSectionCategory() != null){
			hqlStr += " AND siv.sectionCategory = ?";
		}
		if(sectionInfo.getStates() != null){
			hqlStr += " AND siv.states = ?";
		}
		hqlStr += " AND siv.states <> ?";
		final String hql = hqlStr;
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
			throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				int index = -1;
				if(sectionInfo.getSectionCategory() != null){
					query.setEntity(++index, sectionInfo.getSectionCategory());
				}
				if(sectionInfo.getStates() != null){
					query.setInteger(++index, sectionInfo.getStates());
				}
				query.setInteger(++index, IDEDStates.DELETE);
				list = query.list();
				return list;
			}
		});
		return list;
	}
	
	public List<SectionInfoValue> getList() {
		return list;
	}

	public void setList(List<SectionInfoValue> list) {
		this.list = list;
	}

}
